package com.liuss.springchatai.util;

import java.util.List;
import java.util.function.Function;

import com.liuss.springchatai.data.OrderRecord;
import com.liuss.springchatai.service.OrderRecordService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Description;

@Configuration
@Slf4j
public class FunctionTools {
    public record Refund(String orderNumber, String name) {
    }

    public record Query(String orderNumber, String name) {
    }

    @Resource
    private OrderRecordService orderRecordService;

    @Bean
    @Description("退费操作")
    public Function<Refund, String> refund() {
        return request -> {
            List<OrderRecord> list = orderRecordService.list();
            log.info("refund order db : {}", list);
            log.info("refund request info : {},{}", request.orderNumber, request.name);
            // 定位特定的订单记录
            OrderRecord targetRecord = null;
            for (OrderRecord record : list) {
                if (record.getOrderNumber().equals(request.orderNumber) && record.getName().equals(request.name)) {
                    targetRecord = record;
                    break;
                }
            }
            //todo 异步进行退款,回调等操作,这里先进行简单替换.

            if (targetRecord != null) {
                if (targetRecord.getStatus().equals("已支付")) {
                    // 修改查找到的订单记录
                    targetRecord.setStatus("已退款");
                    targetRecord.setRefundAmount(targetRecord.getOrderAmount());
                } else {
                    return "订单状态非已支付,拒绝退款.";
                }
            } else {
                System.out.println("未找到符合条件的订单记录。");
            }
            return request.orderNumber + request.name;
        };
    }

    @Bean
    @Description("查询操作")
    public Function<Query, String> query() {
        return request -> {
            List<OrderRecord> list = orderRecordService.list();
            log.info("query order db : {}", list);
            log.info("query request info : {},{}", request.orderNumber, request.name);
            // 定位特定的订单记录
            OrderRecord targetRecord = null;
            for (OrderRecord record : list) {
                if (record.getOrderNumber().equals(request.orderNumber) && record.getName().equals(request.name)) {
                    targetRecord = record;
                    break;
                }
            }
            return targetRecord == null ? "未查询到订单,请联系客服." : targetRecord.toString();
        };
    }

}